/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xuidemo.provider;

import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.app.Context;

import com.xuexiang.xui_lib.util.UntilTNT;
import com.xuexiang.xuidemo.ResourceTable;

import java.util.List;

/**
 * 适配器
 *
 * @since 2021-03-26
 */
public class SetterProvider extends BaseItemProvider {
    private List<UntilTNT> list = null;
    private Context context;
    private Object object = null;

    /**
     * 构造方法
     *
     * @param list 集合
     * @param context 上下文
     */
    public SetterProvider(List<UntilTNT> list, Context context) {
        this.list = list;
        this.context = context;
    }

    public void setObject(Object object) {
        this.object = object;
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int index) {
        if (list != null && index >= 0 && index < list.size()) {
            return list.get(index);
        }
        return object;
    }

    @Override
    public long getItemId(int index) {
        return index;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        final Component cpt;
        if (component == null) {
            cpt = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_listcontainer_item, null, false);
        } else {
            cpt = component;
        }
        UntilTNT until = list.get(i);
        Text text = (Text) cpt.findComponentById(ResourceTable.Id_item_text);
        Image image = (Image) cpt.findComponentById(ResourceTable.Id_item_img);
        text.setText(until.getName());

        if (until.isDisplay()) {
            image.setVisibility(Component.VISIBLE);
            image.setPixelMap(until.getPicture());
        } else {
            image.setVisibility(Component.HIDE);
        }
        return cpt;
    }
}
